package com.swdegao.iot.netty.utils;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;

/**
 * 对通信原始数据的切除类
 * @Author:AwakeningCode
 * @Date: Created in 11:40 2018\3\11 0011
 */
public class DataResction {


	/**
     * 切除符合协议的数据类型
     * @param data
     * @return
     */
    public static Byte ResctionDataType(Byte dataType){
        return dataType;
    }


	/**
     * 切除符合协议的IMEI和数据域
     * @param data
     * @return
     */
    public static String ResctionIMEIAndBody(String data){
        return data.substring(8,data.length()-6);
    }

    /**
     * 切除符合协议的IMEI
     * @param data
     * @return
     */
    public static byte[] ResctionIMEI(ByteBuf buf){
    	byte[] b = ByteBufUtil.getBytes(buf);
    	byte[] temp = new byte[15];
        System.arraycopy(b, 4, temp, 0, 15);
        return temp;
    }
    /**
     * 切除符合协议的Body
     * @param data
     * @return
     */
    public static byte[] ResctionBody(ByteBuf buf){
    	byte[] b = ByteBufUtil.getBytes(buf);
    	byte[] temp = new byte[b.length-22];
        System.arraycopy(b, 19, temp, 0, temp.length);
        return temp;
    }

	/**
     * 切除符合协议的数据域
     * @param data
     * @return
     */
    public static String ResctionBody(String data){
        return data.substring(30,data.length());
    }


    /**
     * 四联集中器地址
     * @return
     */
    public static String ResctionAddressFieldISILIAN(ByteBuf buf){
        byte[] b = ByteBufUtil.getBytes(buf);
        byte[] temp = new byte[5];
        System.arraycopy(b, 7, temp, 0, temp.length);
        return getAddressFieldPacket(temp);
    }
    /**
     * 地址域
     * @param bit 行政码+设备地址，例如行政0923设备地址0015补充零
     * @return 2309150000 bcd码，前高后低
     */
    public static String getAddressFieldPacket(byte[] bit){
        String address = "";
        byte[] temp = new byte[2];
        System.arraycopy(bit, 0, temp, 0, 2);
        address = get16tobcd(temp,true);

        temp = new byte[2];
        System.arraycopy(bit, 2, temp, 0, 2);
        address = address + get16tobcd(temp,true);
        address = address +"00";
        return address;
    }

    /**
     * 16tobcd 补零,高位在后,eg->0x0c 0x02:0c02
     * @param bit
     * @return
     */
    public static String get16tobcd(byte[] bit,boolean isHIB)
    {
        String str = "";
        for (int i = 0; i < bit.length; i++)
        {
            String temp = Integer.toHexString(bit[i]& 0xFF);
            temp = temp.length() < 2 ? ("0" + temp) : temp;
            str = isHIB? (temp + str):(str + temp);
        }
        return str;
    }


}
